var TableAjax = function () {

    return {

        //main function to initiate the module
        init: function () {
            
            $.fn.modal.Constructor.prototype.enforceFocus = function() {};
            $("#e2").select2({
            minimumInputLength: 1,
            query: function (query) {
                    $.get(baseUrl + "index.php/brandManage/search", {name:query.term}, // 提交的页面
                    function(data) {
                        query.callback(data);
                    });
                }
            });

            if (!jQuery().dataTable) {
                return;
            }

            $("form").validation();

            $(".modal").on('hidden.bs.modal', function () {
              TableAjax.resetForm();
            });

            // begin first table
            $('#sample_1').dataTable({
                "sDom" : "<'row'<'col-md-6 col-sm-12'l><'col-md-12 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", //default layout without horizontal scroll(remove this setting to enable horizontal scroll for the table)
                "aLengthMenu": [
                    [10, 25, 50, 100, -1],
                    [10, 25, 50, 100, "All"] // change per page values here
                ],
                "bProcessing": false,
                "bServerSide": true,
                "sAjaxSource": baseUrl+"index.php/salesManage/getList",
                // set the initial value
                "iDisplayLength": 10,
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sProcessing": '<i class="fa fa-coffee"></i>&nbsp;Please wait...',
                    "sLengthMenu": "_MENU_ records",
                    "oPaginate": {
                        "sPrevious": "Prev",
                        "sNext": "Next"
                    }
                },
                // "aoColumnDefs": [{
                //         'bSortable': false,
                //         'aTargets': [0]
                //     }
                // ]
            });

            jQuery('#sample_1_wrapper .dataTables_filter input').addClass("form-control input-medium"); // modify table search input
            jQuery('#sample_1_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown

            // handle record edit/remove
            $('body').on('click', '#sample_1_wrapper .btn-editable', function() {
                $.get(baseUrl+"index.php/salesManage/getById",{id:$(this).attr("data-id")},   // 提交的页面
                    function(data) {
                        $('.modal').modal("show");

                        $('input[name=id]').val(data._id);
                        $('input[name=nickname]').val(data.nickname);
                        $('input[name=shop]').val(data.shop);
                        $('input[name=telephone]').val(data.telephone);
                        $('input[name=email]').val(data.email);
                        $('input[name=brand]').val(data.brand);
                        $('#e2').prev().find('.select2-chosen').text(data.brandname);
                        $('input[name=account]').val(data.account);
                        $('input[name=password]').val(data.password);
                    }
                );
            });

            $('body').on('click', '#sample_1_wrapper .btn-removable', function() {
                var data_id = $(this).attr("data-id");
                bootbox.confirm("Are you sure?", function(result) {
                    if(!result)return;
                    $.get(baseUrl+"index.php/salesManage/delete",{id:data_id},   // 提交的页面
                        function(data) {
                            var $lmTable = $("#sample_1").dataTable( { bRetrieve : true } );
                            $lmTable.fnDraw();
                        }
                    );
                });
            });

            $('.fileUpload').each(function(){
                
                $(this).click(function(){
                    $(this).prev().click();
                });

                var fileName = $(this).next();
                $(this).prev().fileupload({
                        url: baseUrl+"index.php/site/upload",
                        dataType: 'json',
                        autoUpload: true,

                        done: function (e, data) {
                            $.each(data.result.files, function (index, file) {
                                //$('<p/>').text(file.name).appendTo('#files');
                                fileName.val(file.url);
                                fileName.prev().attr("src",baseUrl+file.url);
                            });
                        },
                });

            });
             $('#addForm').submit(function(){
                if ($("form").valid()==false)
                return false;
            
                 $.ajax({
                    url: baseUrl+"index.php/salesManage/add",   // 提交的页面
                    data: $('#addForm').serialize(), // 从表单中获取数据
                    type: "POST",                   // 设置请求类型为"POST"，默认为"GET"
                    error: function(request) {      // 设置表单提交出错
                        alert(request.statusText);
                        return false;
                    },
                    success: function(data) {
                        $(".modal").modal("toggle");
                        var $lmTable = $("#sample_1").dataTable( { bRetrieve : true } );
                        $lmTable.fnDraw();
                        }
                    });
                return false;
            });
        },
        resetForm:function(){
            $('#addForm')[0].reset();
            $('input[name=id]').val("");
            $("form").validation();
            $('#e2').prev().find('.select2-chosen').text("选择品牌");
            $('#e2').select2('val','');

            $('.fileUpload').each(function(){
                    $(this).attr("src","assets/fileUpload.jpg");
                });
            }

    };

}();